<template>
  <div class="main-div">
    <div class="main-search-div">
      <el-form
          :model="searchItem"
          ref="searchItemRef"
          label-width="100px"
          label-suffix=":"
          inline
      >
        <el-form-item label="菜单名称" prop="roleName" class="main-search-item-3">
          <el-input v-model="searchItem.menuName"></el-input>
        </el-form-item>
        <el-form-item label="所属模块" prop="roleType" class="main-search-item-3">
          <el-select v-model="searchItem.moduleId" :clearable="true" placeholder="请选择!">
            <el-option v-for="item in moduleData" :key="item.key||item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否使用" prop="isUse" class="main-search-item-3">
          <el-select v-model="searchItem.isUse" :clearable="true" placeholder="请选择!">
            <el-option v-for="item in isUseData" :key="item.key||item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" :loading="searchLoading">查询</el-button>
          <el-button @click="reset(searchItemRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-button-div">
      <el-button type="primary" @click="addMenuFn">新增</el-button>
      <el-popconfirm title="是否删除?" @confirm="delMenuFn(0)">
        <template #reference>
          <el-button type="danger">删除</el-button>
        </template>
      </el-popconfirm>
    </div>
    <div class="main-table-div">
      <el-table
          :data="tableData"
          :border="true"
          row-key="id"
          highlight-current-row
          @current-change="handleCurrentChange"
      >
        <el-table-column prop="node.menuName" label="菜单名" width="auto" fixed="left" align='left' header-align="center"/>
        <el-table-column prop="node.menuPath" label="菜单路径" width="auto" align='left' header-align="center"/>
        <el-table-column prop="node.menuTypeLabel" label="菜单类型" width="auto" align='center'/>
        <el-table-column prop="node.orderNum" label="菜单排序" width="auto" align='center'/>
        <el-table-column prop="node.isUseLabel" label="是否使用" width="auto" align='center'/>
        <el-table-column prop="node.owningModuleLabel" label="所属模块" width="auto" align='center'/>

        <el-table-column align="center" fixed="right" label="操作" width="200px">
          <template #default="scope">
              <el-button size="small" type="primary" round @click="handleEdit(scope.row)">编辑</el-button>
              <el-button size="small" type="warning" round @click="addRole(scope.row)" v-if="scope.row.node.menuType == 2">新增角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <menu-save-dialog
      :show-dialog="saveItem.showDialog"
      :title="saveItem.title"
      :dialog-type="saveItem.dialogType"
      :dialog-param="saveItem.dialogParam"
      @handleCloseDialog="handleCloseSaveDialog($event)"
      @handleClosedDialog="handleClosedSaveDialog($event)"
      @handleOpenDialog="handleOpenSaveDialog"
      @handleOpenedDialog="handleOpenedSaveDialog"
  ></menu-save-dialog>
  <el-dialog v-model="showTip"
             title="提示"
             :destroy-on-close="false"
             :close-on-click-modal="false">
    <span>{{tipContent}}</span>
    <template #footer>
      <el-button type="primary" @click="tipConfirm">确认</el-button>
      <el-button type="danger" @click="tipCancel">取消</el-button>
    </template>
  </el-dialog>
  <relation-transfer :show-dialog="relationTransfer.showDialog"
                     :title="relationTransfer.title"
                     :relation-id="relationTransfer.relationId"
                     :relation-type="relationTransfer.relationType"
                     @handleOpenDialog="openRelationTransfer"
                     @handleCloseDialog="closeRelationTransfer($event)"
                     @confirmRelation="handleConfirmRelation($event)"
  >
  </relation-transfer>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import type {FormInstance} from "element-plus";
import {RESPONSE_CODE_SUCCESS, RESPONSE_CODE_TIP_202} from "@/config/common-config.ts";
import {delMenuReq, getMenuTreeListReq, saveMenuRoleIdsReq} from "@/api/admin/menu.ts";
import {dictDataUtil} from "@/utils/common-request.ts";
import {SYSTEM_MENU_IS_USE, SYSTEM_MODULE} from "@/constants/dict-constants.ts";
import MenuSaveDialog from "@/components/manager/menu/MenuSaveDialog.vue";
import {DIALOG_ADD, DIALOG_EDIT, RELATION_TYPE_MENU} from "@/constants/common-constant.ts";
import {checkIsNull} from "@/utils/check-utils.ts";
import {elMessageTip, errorMessageTip, successMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import RelationTransfer from "@/components/manager/relation/RelationTransfer.vue";
import {saveUserRoleIdsReq} from "@/api/admin/user.ts";

interface SearchItem {
  menuName: string;
  moduleId: string;
  isUse: string;
}

interface SaveItem {
  showDialog: boolean;
  title: string;
  dialogType: string;
  dialogParam: any;
}

const searchItem = reactive<SearchItem>({
  menuName: '',
  moduleId: '',
  isUse: ''
})

const saveItem = reactive<SaveItem>({
  showDialog: false,
  title: '',
  dialogType: '',
  dialogParam: {}
})

interface RelationTransfer {
  showDialog: boolean;
  title: string;
  relationId: string;
  relationType: string;
}

const relationTransfer = reactive<RelationTransfer>({
  showDialog: false,
  title: '',
  relationId: '',
  relationType: ''
})

const initModuleData = async () => {
  moduleData.value = await dictDataUtil(SYSTEM_MODULE)
}

const initIsUseData = async () => {
  isUseData.value = await dictDataUtil(SYSTEM_MENU_IS_USE)
}

const searchItemRef = ref<FormInstance>()

const searchLoading = ref<boolean>(false);

const moduleData = ref<any>(() => {
});

const isUseData = ref<any>(() => {
});

const tableData = ref<any[]>([]);

const search = async () => {
  searchList().then();
}

const searchList = async () => {
  searchLoading.value = true;
  const params = {
    menuName: searchItem.menuName,
    owningModule: searchItem.moduleId,
    isUse: searchItem.isUse
  }
  const res: any = await getMenuTreeListReq(params)
  searchLoading.value = false
  if (res.code === RESPONSE_CODE_SUCCESS) {
    tableData.value = res.data;
  }
}

const handleEdit = (row: any) => {
  saveItem.showDialog = true
  saveItem.title = '编辑'
  saveItem.dialogType = DIALOG_EDIT
  saveItem.dialogParam = row
}

const addRole = (row: any) => {
  relationTransfer.showDialog = true;
  relationTransfer.title = row.node.menuName + '角色分配';
  relationTransfer.relationId = row.node.id;
  relationTransfer.relationType = RELATION_TYPE_MENU
}

const reset = (formEl: any) => {
  if (!formEl) return;
  formEl.resetFields();
}

const selectRow = ref<any>({});
const handleCurrentChange = (row: any) => {
  selectRow.value = row;
}

const addMenuFn = () => {
  saveItem.showDialog = true
  saveItem.title = '新增'
  saveItem.dialogType = DIALOG_ADD
  saveItem.dialogParam = {}
}

const showTip = ref<boolean>(false)
const tipContent = ref<string>('')
const tipConfirm = async () => {
  showTip.value = false
  await delMenuFn(1);
}
const tipCancel = () => {
  showTip.value = false
}
const delMenuFn = async (secMark: number) => {
  const currentRow = selectRow.value
  if (checkIsNull(currentRow)){
    warningMessageTip("请至少选择一条数据")
    return
  }

  const params = {
    id: currentRow.id,
    secMark: secMark
  }
  const res: any = await delMenuReq(params)
  if (res.code === RESPONSE_CODE_SUCCESS) {
    searchList().then()
    successMessageTip(res.message)
  } else if (res.code === RESPONSE_CODE_TIP_202){
    showTip.value = true
    tipContent.value = res.message
  } else {
    errorMessageTip(res.message)
  }
}

const handleCloseSaveDialog = (val: boolean) => {
  saveItem.showDialog = val
}

const handleClosedSaveDialog = (val: boolean) => {
  saveItem.showDialog = val
  searchList().then()
}

const handleOpenSaveDialog = () => {

}

const handleOpenedSaveDialog = () => {

}

const openRelationTransfer = () => {

}

const closeRelationTransfer = (val: boolean) => {
  relationTransfer.showDialog = val
}

const handleConfirmRelation = async (data: any) => {
  const params = {
    id: data.relationId,
    roleList: data.selectInfo
  }
  const res: any = await saveMenuRoleIdsReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS){
    relationTransfer.showDialog = false
  }
}
onMounted(async () => {
  searchList().then();
  initModuleData().then()
  initIsUseData().then()
})
</script>

<style scoped>

</style>